package com.wngz.school.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wngz.school.entity.Teacher;
import com.wngz.school.mapper.TeacherMapper;
import com.wngz.school.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String REDIS_KEY = "teacherPage";

    @Override
    public Page<Teacher> query(Integer pageNumber, Integer pageSize, Map<String, Object> params) {
        String cacheKey = REDIS_KEY + ":" + pageNumber + ":" + pageSize;

        // 1. 尝试从 Redis 缓存中获取数据
        Page<Teacher> cachedPage = (Page<Teacher>) redisTemplate.opsForValue().get(cacheKey);

        if (cachedPage != null) {
            // 2. 如果缓存中存在数据，直接返回
            System.out.println("从缓存中获取数据...");
            return cachedPage;
        }

        // 3. 如果缓存中没有，查询数据库
        Page<Teacher> page = new Page<>(pageNumber, pageSize);
        Page<Teacher> teacherPage = teacherMapper.selectPage(page, null);

        // 4. 将查询到的数据缓存到 Redis 中，设置过期时间（例如 10 分钟）
        redisTemplate.opsForValue().set(cacheKey, teacherPage, 10, TimeUnit.MINUTES);

        System.out.println("从数据库中查询数据并缓存...");
        return teacherPage;
    }

    @Override
    public void removeById(Integer id) {
        // 1. 删除数据库中的数据
        teacherMapper.deleteById(id);

        // 2. 清空 Redis 中的相关缓存
        clearCache();
    }

    // 清空分页缓存的方法
    private void clearCache() {
        // 清除 Redis 中所有与 "teacherPage" 相关的缓存键
        Set<String> keys = redisTemplate.keys(REDIS_KEY + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
            System.out.println("清空 Redis 缓存...");
        }
    }
}

